from service.constructAnomalyChain import consAnomalyChain

metric_map = {
    'ResponseTime': 100014,
    'ErrorCount': 100015,
    'QueryPerSecond': 100016
}


def calTopK(graph, anomalous_services, k):
    all_paths = []
    all_services = graph['nodes']
    for s in all_services:
        s['rank_score'] = 0
    for service in anomalous_services:
        for metric in service['anomalous_metrics']:
            path = consAnomalyChain(graph, service['id'], metric_map[metric], anomalous_services)
            all_paths.append(path)
    for path in all_paths:
        for i in range(0, len(path)):
            service_id = path[i]['id']
            service = [item for item in all_services if item['id'] == service_id][0]
            service['rank_score'] += service['score'] * (1 - i / len(path))
    sorted(all_services, key=lambda x: x['rank_score'])
    root_cause_list = all_services[:k]
    for item in root_cause_list:
        service = [i for i in all_services if i['id'] == item['id']][0]
        service['status'] = 2
    return graph

